//
//  JSMSearchViewController.m
//  TakeYouTourTogether
//
//  Created by dllo on 15/12/1.
//  Copyright © 2015年 king. All rights reserved.
//

#import "JSMSearchViewController.h"
#import "JSMTouringModel.h"
#import "JSMDetailsViewController.h"
@interface JSMSearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong)UISearchBar *touringSearchBar;
@property(nonatomic, strong)BaseTableView *touringtableView;
@property(nonatomic, strong)NSString *searchStr;
@property(nonatomic, strong)NSMutableArray *searchArr;
@end

@implementation JSMSearchViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.searchArr = [NSMutableArray array];
    self.searchArr = [[JSMHistoryTool historyBaseHandle] selectAllHistory];
    [self.touringtableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"qingchuyuhuancun"] style:UIBarButtonItemStylePlain target:self action:@selector(clearHistory)];
    [self createTableView];
    [self createSearchBar];
    
}
#pragma mark - create searchBar
- (void)createSearchBar{
    self.touringSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 0, 50)];
    self.touringtableView.tableHeaderView = self.touringSearchBar;
    self.touringSearchBar.placeholder = @"古道、雪山、梯田、草原、沙漠";
    self.touringSearchBar.delegate = self;
    [self.touringSearchBar setShowsCancelButton:YES animated:YES];
}

#pragma mark - create tableView
- (void)createTableView{
    self.touringtableView = [[BaseTableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.touringtableView];
    [self.touringtableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.touringtableView.delegate = self;
    self.touringtableView.dataSource= self;
    self.touringtableView.bounces = NO;
}
#pragma mark - clear
- (void)clearHistory{
    for (JSMTouringModel *model in self.searchArr) {
        if ([[JSMHistoryTool historyBaseHandle]isHaveHistory:model]== InTable) {
            [[JSMHistoryTool historyBaseHandle]deleteHistory:model];
        }
    }
    self.searchArr = [[JSMHistoryTool historyBaseHandle] selectAllHistory];
    [self.touringtableView reloadData];
}
#pragma mark - cancel
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.touringSearchBar resignFirstResponder];
}

#pragma mark - search
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.touringSearchBar resignFirstResponder];
    searchBar.text = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.searchStr = [searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:searchBar.text]];
    [self createDate];
}
#pragma mark 解析数据
- (void)createDate{
    [AFNetworkingTool getUrl:[NSString stringWithFormat:@"http://tubu.ibuzhai.com/rest/v2/trails?&page_size=20&area_id=&page=1&search=%@&device_type=2&app_version=4.3.3&api_version=1&access_token=",self.searchStr]hudSuperView:self.view result:JSON success:^(id result) {
        NSDictionary *dic = result;
        if ([dic[@"trails"] count] == 0) {
            UIAlertController *alertcontroller = [UIAlertController alertControllerWithTitle:@"提示" message:@"未搜索到结果" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertcontroller addAction:cancelAction];
            [self presentViewController:alertcontroller animated:YES completion:^{
            }];
        }else{
            self.searchArr = [JSMTouringModel baseModelByArr:dic[@"trails"]];
            [self.touringtableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark - tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"reuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    JSMTouringModel *myModel =  self.searchArr[indexPath.row];
    NSMutableAttributedString *titleAttributedString = [[NSMutableAttributedString alloc] initWithString:myModel.name];
    NSRange titleRange = [myModel.name rangeOfString:self.touringSearchBar.text];
    [titleAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:titleRange];
    cell.textLabel.attributedText = titleAttributedString;
    cell.detailTextLabel.text = myModel.destination;
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    return cell;
}
#pragma mark - 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([[JSMHistoryTool historyBaseHandle]isHaveHistory:self.searchArr[indexPath.row]]== NotInTable) {
        [[JSMHistoryTool historyBaseHandle]saveHistory:self.searchArr[indexPath.row]];
    }
    JSMDetailsViewController *detailsVc = [[JSMDetailsViewController alloc]init];
    detailsVc.detailModel = self.searchArr[indexPath.row];
    [self.navigationController pushViewController:detailsVc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
